import json
import re
import os
from typing import Dict, List

class AdvancedHexBinConverter:
    def __init__(self, segment_size = 272):
        self.segment_size = segment_size
        self.hex_pattern = re.compile(r'[0-9A-Fa-f]{2}')

    def __validate_hex(self, hex_str):
        hex_bytes = []
        for match in self.hex_pattern.finditer(hex_str):
            try:
                val = int(match.group(), 16)
                hex_bytes.append(val)
            except ValueError:
                continue
        return bytes(hex_bytes)
    
    def _process_entry(self, hex_list):
        merged = ''.join([h.replace(' ', ' ') for h in hex_list])

        bin_data = self.__validate_hex(merged)

        data_len = len(bin_data)
        if data_len > self.segment_size:
            return bin_data[:self.segment_size]
        elif data_len < self.segment_size:
            return bin_data + bytes([0] * (self.segment_size - data_len))
        return bin_data
    
    def convert(self, input_json, output_bin):
        with open(input_json, 'r') as f:
            data: Dict[str, List[str]] = json.load(f)
        
        total = len(data)
        success = 0

        with open(output_bin, 'wb') as bin_file:
            for key, hex_list in data.items():
                try:
                    segment = self._process_entry(hex_list)
                    bin_file.write(segment)
                    success += 1
                except Exception as e:
                    print(f"记录 {key} 处理失败: {str(e)}")
                    continue
        
        print(f"转换统计 | 总数: {total} | 成功: {success} | 失败: {total-success}")
        return (total, success, total-success)

if __name__ == "__main__":
    converter = AdvancedHexBinConverter()

    try:
        total, success, _ = converter.convert(
            input_json="0x00_0x0000_mctp.json",
            output_bin = "0x00_0x0000_mctp.bin"
        )

        expected_size = success * 272
        actual_size = os.path.getsize("./0x00_0x0000_mctp.bin")
        if actual_size != expected_size:
            raise RuntimeError(f"完整性校验失败： 预期{expected_size}字节， 实际{actual_size}字节")
        
        print(f"生成文件验证通过: {actual_size}字节")
    
    except Exception as e:
        print(f"严重错误:{str(e)}")